const express = require("express")
const router = express.Router();
const fs = require("fs")
const multer = require("multer")
const R = require("../util/resultJson.js")


router.post("/",multer({dest:"./temp"}).single("file"),function (req,res) {
    const mts = req.file.mimetype.split("/");
    const mimetype = mts[mts.length-1];
    const fileName = req.file.filename+"."+mimetype;
    const type = req.body.type || "goods";
    const d = new Date();
    const year = d.getFullYear();
    const month = d.getMonth()+1;
    const date = d.getDate();

    const publicPath = "public";
    const filePath = `/upload/${type}/${year}/${month < 10 ? '0' + month : month}/${date < 10 ? '0' + date : date}/`

    if(!fs.existsSync(publicPath+filePath)){
        fs.mkdirSync(publicPath+filePath,{ recursive: true });
    }

    fs.readFile(req.file.path,function (e,d) {
        if(e){
            res.json(R.error(e.message));
        }else{
            fs.writeFile(publicPath+filePath+fileName,d,function (e) {
                fs.unlinkSync(req.file.path)
                if(e){
                    res.json(R.error(e.message));
                }else{
                    res.json(R.success(filePath+fileName));
                }
            })
        }
    })
})
module.exports = router;
